package com.share.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.share.constant.Result;
import com.share.constant.StatusCode;
import com.share.holder.UUIDHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.share.constant.DefaultConstant.*;

@Component
public class CaptchaInterceptor implements HandlerInterceptor {
    @Autowired
    ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 获取用户验证码对应的uuid
        String uuid = request.getHeader(X_CAPTCHA_UUID);
        //2. 判断是否为空
        if (uuid == null) {
            response.setStatus(401);
            Result result = Result.fail(StatusCode.CAPTCHA_ERROR.getCode(), StatusCode.CAPTCHA_ERROR.getMessage());
            response.getWriter().write(objectMapper.writeValueAsString(result));
            return false;
        }
        //3.不等于空，将uuid放入threadlocal中，保证线程安全
        UUIDHolder.set(uuid);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //4. 移除threadlocal中的数据, 防止内存泄露
        UUIDHolder.clear();
    }

}
